#!/usr/bin/env python
import sys, os

def print_resp(r):
	a = r.split('\n')
	for i in a:
		e = i.find('\t')
		if e != -1:
			print '\033[1m%s\033[0m%s' % (i[:e], i[e:])
		else:
			print i

def main(devel = False):
	a = sys.argv[1:]
	if len(a) == 0:
		# todo print help
		return
	isCfgFile = False
	if os.path.exists(a[0]):
		isCfgFile = True
	if len(a) == 1 and isCfgFile:
		a.append('run')

	if len(a) == 2 and a[1] in ['run', 'start', 'restart', 'stop'] and isCfgFile:
		from utils import config
		if config.readConfig(a[0]) == False:
			# need to log what is wrong with config file
			from glog import GLog
			GLog().emergency_quit()
			return 1
		main = config.get_obj('main')
		if main is None:
			from glog import GLog
			GLog().emergency_quit()
			return 1

		if a[1] == 'restart' or a[1] == 'stop':
			main.kill_pid_from_pidfile()
	
		if a[1] == 'stop':
			return 0

		daemonize = True
		if a[1] == 'run':
			daemonize = False
		main.daemonize = daemonize
		main.start()
	else:
		from config import Config
		config = Config()
		if config.readConfig(a[0]) == False:
			from glog import GLog
			GLog().emergency_quit()
			return 1
		main = config.get_obj('main')
		if main is None:
			from glog import GLog
			GLog().emergency_quit()
			return 1

		if config.main.preferred_ipc == 'zmq':
			from gevent_zeromq import zmq
			from gevent import Timeout
			from gevent.pool import Pool
			p = Pool(1)

			context = zmq.Context()
			socket = context.socket(zmq.REQ)
			socket.connect(main.socket)
			r = ''

			with Timeout(1):
				try:
					socket.send_pyobj(' '.join(a[1:]))
					r = p.spawn(socket.recv)
					p.join()
				except Timeout:
					print 'Timeout - no response from server'
					return 1
				except Exception, e:
					print e
					return 1

			r = r.get()
			if (len(r) > 1 and r[:2] == '0\n'):
				print_resp(r[2:])
				return 0

			timeout = float(r)
			print 'Max wait time: %f' % timeout
			with Timeout(timeout + 0.2):
				a = None
				try:
					socket.send_pyobj('ok')
					a = socket.recv()
				except Timeout:
					print "Timeout - no response from server in %fs." % timeout
				except Exception, e:
					print e
				else:
					print_resp(a)
		else:
			import xmlrpclib
			if config.xmlrpc_host == '':
				config.xmlrpc_host = '127.0.0.1'
			proxy = xmlrpclib.ServerProxy('http://%s:%d/' % (config.xmlrpc_host, config.xmlrpc_port))
			print str(proxy.cmd(' '.join(a[1:])))

if __name__ == "__main__":
	main()

__all__ = ['main']

